package vip.xiaonuo.smzq.modular.kcl.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.net.URLDecoder;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.multipart.MultipartFile;
import vip.xiaonuo.auth.core.pojo.SaBaseLoginUser;
import vip.xiaonuo.auth.core.util.StpLoginUserUtil;
import vip.xiaonuo.common.util.CommonDownloadUtil;
import vip.xiaonuo.common.util.CommonFileUtil;
import vip.xiaonuo.smzq.core.tools.file.PathUtils;
import vip.xiaonuo.smzq.modular.kcl.entity.*;
import vip.xiaonuo.smzq.modular.kcl.entity.vo.ExportTable;
import vip.xiaonuo.smzq.modular.kcl.mapper.*;
import vip.xiaonuo.smzq.modular.kcl.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import vip.xiaonuo.common.page.CommonPageRequest;
import vip.xiaonuo.smzq.modular.synchronize.service.impl.ISynchDataService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 数据管理mdb导入 服务实现类
 *
 * @author sqq
 * @since 2024-03-25
 */
@Service
public class SjglServiceImpl extends ServiceImpl<SjglMapper, Sjgl> implements ISjglService {

    @Resource
    private SjglMapper sjglMapper;
    @Resource
    private KsMapper ksMapper; //矿山基本信息

    @Resource
    private KsshjlMapper iKsshjlMapper; //矿山审核记录表

    @Resource
    private ZyclMapper iZyclMapper;//资源储量

    @Resource
    private ZbMapper iZbMapper;//坐标

    @Resource
    private KsjjMapper iKsjjMapper;//矿山经济

    @Resource
    private KcpMapper iKcpMapper;//矿产品

    @Resource
    private CxhMapper iCxhMapper;//采选环

    @Resource
    private ZhhsMapper iZhhsMapper;//综合回收

    @Resource
    private DztjMapper iDztjMapper;//地质条件

    @Resource
    private BgMapper iBgMapper;//报告

    @Resource
    private YfMapper iYfMapper;//压覆

    @Resource
    private BazyclMapper iBazyclMapper;//备案资源储量

    @Resource
    private ZlscMapper iZlscMapper;//文件上传

    @Resource
    private WjglbMapper iWjglbMapper;//资料关联
    @Resource
    private CkqsqdjMapper iCkqsqdjMapper;//采矿权登记
    @Resource
    private TkqsqdjMapper iTkqsqdjMapper;//探矿权登记

    @Autowired
    private ISynchDataService synchDataService;

    @Autowired
    protected HttpServletResponse response;
    @Value("${file.base}")
     String baseFilePath;

    @Override
    public Page<Sjgl> page(Sjgl sjgl) {
        QueryWrapper<Sjgl> queryWrapper = new QueryWrapper<>();
        if (sjgl.getNd() != null) {
            queryWrapper.eq("nd", sjgl.getNd());
        }
        if (sjgl.getMc() != null) {
            queryWrapper.like("mc", sjgl.getMc());
        }
        if (sjgl.getScsj() != null && sjgl.getScsj().contains("-")) {
            String kssj = sjgl.getScsj().substring(0, 9);
            String jssj = sjgl.getScsj().substring(11);
            queryWrapper.between("scsj", kssj, jssj);
        }
        queryWrapper.eq("sjlb", sjgl.getSjlb());
        queryWrapper.orderByDesc("scsj");


        return this.page(CommonPageRequest.defaultPage(), queryWrapper);
    }

    /**
     * 根据年度删除信息
     *
     * @param pkid
     * @return
     */
    @Override
    public String deleteList(String pkid) {
        String result = "删除成功";
        try {

            Sjgl sjgl = sjglMapper.selectById(pkid);
            //删除储量填报相关数据
            deleteCltbData(sjgl.getNd());
            //删除数据管理mdb导入等详情数据
            sjglMapper.deleteById(pkid);


        } catch (Exception e) {
            result = "删除失败";
        }
        return result;
    }

    @Override
    public Boolean getIfExistence(Sjgl sjgl) {
        Boolean ifExistence = false;
        List<Sjgl> sjglList = new ArrayList<>();
        QueryWrapper<Sjgl> querySjgl = new QueryWrapper<>();
        querySjgl.eq("nd", sjgl.getNd());
        sjglList = sjglMapper.selectList(querySjgl);
        if (sjglList.size() > 0) {
            ifExistence = true;
        }

        return ifExistence;
    }


    public void deleteCltbData(Integer nd) {
        try {
            //删除矿山基本信息
            QueryWrapper<Ks> queryKs = new QueryWrapper<>();
            queryKs.eq("nd", nd);
            ksMapper.delete(queryKs);
            //删除矿山审核记录表
            QueryWrapper<Ksshjl> queryKsshjl = new QueryWrapper<>();
            queryKsshjl.eq("nd", nd);
            iKsshjlMapper.delete(queryKsshjl);
            //删除资源储量
            QueryWrapper<Zycl> queryZycl = new QueryWrapper<>();
            queryZycl.eq("nd", nd);
            iZyclMapper.delete(queryZycl);
            //删除坐标
            QueryWrapper<Zb> queryZb = new QueryWrapper<>();
            queryZb.eq("nd", nd);
            iZbMapper.delete(queryZb);
            //删除矿山经济
            QueryWrapper<Ksjj> queryKsjj = new QueryWrapper<>();
            queryKsjj.eq("nd", nd);
            iKsjjMapper.delete(queryKsjj);
            //删除矿产品
            QueryWrapper<Kcp> queryKcp = new QueryWrapper<>();
            queryKcp.eq("nd", nd);
            iKcpMapper.delete(queryKcp);
            //删除采选环
            QueryWrapper<Cxh> queryCxh = new QueryWrapper<>();
            queryCxh.eq("nd", nd);
            iCxhMapper.delete(queryCxh);
            //删除综合回收
            QueryWrapper<Zhhs> queryZhhs = new QueryWrapper<>();
            queryZhhs.eq("nd", nd);
            iZhhsMapper.delete(queryZhhs);
            //删除地质条件
            QueryWrapper<Dztj> queryDztj = new QueryWrapper<>();
            queryDztj.eq("nd", nd);
            iDztjMapper.delete(queryDztj);
            //删除报告
            QueryWrapper<Bg> queryBg = new QueryWrapper<>();
            queryBg.eq("nd", nd);
            iBgMapper.delete(queryBg);
            //删除压覆
            QueryWrapper<Yf> queryYf = new QueryWrapper<>();
            queryYf.eq("nd", nd);
            iYfMapper.delete(queryYf);
            //删除备案资源储量
            QueryWrapper<Bazycl> queryBazycl = new QueryWrapper<>();
            queryBazycl.eq("nd", nd);
            iBazyclMapper.delete(queryBazycl);
            //删除文件上传
            QueryWrapper<Zlsc> queryZlsc = new QueryWrapper<>();
            queryZlsc.eq("nd", nd);
            iZlscMapper.delete(queryZlsc);
            //删除资料关联
            QueryWrapper<Wjglb> queryWjglb = new QueryWrapper<>();
            queryWjglb.eq("nd", nd);
            iWjglbMapper.delete(queryWjglb);
            //删除采矿权登记
            QueryWrapper<Ckqsqdj> queryCkqsqdj = new QueryWrapper<>();
            queryCkqsqdj.eq("nd", nd);
            iCkqsqdjMapper.delete(queryCkqsqdj);
            //删除探矿权登记
            QueryWrapper<Tkqsqdj> queryTkqsqdj = new QueryWrapper<>();
            queryTkqsqdj.eq("nd", nd);
            iTkqsqdjMapper.delete(queryTkqsqdj);
        } catch (Exception e) {
            System.out.println(e);
        }

    }


    /**
     * mdb文件导入
     *
     * @param file
     * @param sjgl
     * @return
     */

    @Override
    public Boolean fileUploadMdb(MultipartFile file, Sjgl sjgl) {
        String result = "";
        Boolean ifExistence = false;
//        List<Sjgl> sjglList = new ArrayList<>();
//        QueryWrapper<Sjgl> querySjgl = new QueryWrapper<>();
//        querySjgl.eq("nd", sjgl.getNd());
//        querySjgl.eq("sjlb", sjgl.getSjlb());
//        sjglList = sjglMapper.selectList(querySjgl);
//        if (sjglList.size() > 0) {
//            ifExistence = true;
//        } else {
            //文件名称
            String fileName = file.getOriginalFilename();
            fileName = URLDecoder.decode(fileName, StandardCharsets.UTF_8);//解码
            String suffix = fileName.substring(fileName.lastIndexOf("."));
            // String wjName = fileName.substring(0, fileName.lastIndexOf("."));

            File file1 = new File(PathUtils.getUpLoadPath(baseFilePath) + File.separator +  sjgl.getMc() + suffix);
            if (!suffix.toLowerCase().equals(".mdb")) {
                result += "[" + fileName + "]文件格式错误";
            } else {
                try {
                    FileUtils.copyInputStreamToFile(file.getInputStream(), file1);
                    //同步数据
                    synchDataService.tbData(file1.getPath(), sjgl.getNd());
                } catch (Exception e) {
                    result = String.valueOf(e);
                    System.out.println(e);
                }
                sjgl.setMc(file1.getName());
                sjgl.setPkid(UUID.randomUUID().toString());
                sjgl.setScsj(DateUtil.format(new Date(), "YYYYMMdd"));
                SaBaseLoginUser saBaseLoginUser = StpLoginUserUtil.getLoginUser();
                sjgl.setScr(saBaseLoginUser.getName());
                int ifSuccess = sjglMapper.insert(sjgl);
                if (ifSuccess > 0) {
                    result = "[" + file1.getName() + "]" + "数据导入成功";
                }
            }
//        }
        System.out.println(result);
        return ifExistence;
    }

    /**
     * mdb文件导入
     *
     * @param file
     * @param sjgl
     * @return
     */

    @Override
    public String fileUploadMdb2(MultipartFile file, Sjgl sjgl) {
        String result = "";
        //根据年度删除数据
        deleteCltbData(sjgl.getNd());
        /*  for (MultipartFile file : files) {*/
        //文件名称
        String fileName = file.getOriginalFilename();
        fileName = URLDecoder.decode(fileName, StandardCharsets.UTF_8);//解码
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        // String wjName = fileName.substring(0, fileName.lastIndexOf("."));

        File file1 = new File(PathUtils.getUpLoadPath(baseFilePath) + File.separator + sjgl.getMc() + suffix);
        if (!suffix.toLowerCase().equals(".mdb")) {
            result += "[" + fileName + "]文件格式错误";
        } else {
            try {
                FileUtils.copyInputStreamToFile(file.getInputStream(), file1);
                synchDataService.tbData(file1.getPath(), sjgl.getNd());
            } catch (Exception e) {
                result = String.valueOf(e);
                System.out.println(e);
            }
            sjgl.setMc(file1.getName());
            sjgl.setPkid(UUID.randomUUID().toString());
            sjgl.setScsj(DateUtil.format(new Date(), "YYYYMMdd"));
            SaBaseLoginUser saBaseLoginUser = StpLoginUserUtil.getLoginUser();
            sjgl.setScr(saBaseLoginUser.getName());
            int ifSuccess = sjglMapper.insert(sjgl);
            if (ifSuccess > 0) {
                result = "[" + file1.getName() + "]" + "数据导入成功";
            }

        }

//        }

        return result;
    }


    /**
     * mdb文件导出
     *
     * @param nd
     * @return
     */
    @Override
    public void fileExport(Integer nd, Integer sjlb,HttpServletResponse response) {

        if (sjlb == 1) {

        } else if (sjlb == 2) {

        } else if (sjlb == 3) {

        } else if (sjlb == 4) {
            getClsj(nd, response);
        }

    }

    /**
     * 储量数据导出
     *
     * @param nd
     * @param response
     * @return
     */
    public void getClsj(Integer nd, HttpServletResponse response) {


        String baseName = nd + "年储量数据";
        String basePath = PathUtils.getUpLoadPath(baseFilePath);
        String resultFile = basePath + File.separator + baseName + ".mdb";

        File file = new File(basePath);
        if (!file.exists()) {
             file.mkdirs();
        }

        boolean result =  synchDataService.exportMdb(nd, resultFile);

        System.out.println(resultFile);
        if (result) {
            File mdbFile = new File(resultFile);
//                CommonDownloadUtil.download(mdbFile, response);

            // 设置正确的MIME类型给MDB文件
            response.setContentType("application/vnd.ms-access");
            String encodedFileName = null;
            try {
                encodedFileName = URLEncoder.encode(mdbFile.getName(), "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            response.setHeader("Content-Disposition", "attachment;filename=" + encodedFileName);

            try (InputStream in = new FileInputStream(mdbFile);
                 OutputStream out = response.getOutputStream()) {
                byte[] buffer = new byte[4096];
                int bytesRead;
                while ((bytesRead = in.read(buffer)) != -1) {
                    out.write(buffer, 0, bytesRead);
                }
            }catch (Exception e){
                e.printStackTrace();
            }


        }

    }
}
